package com.example.musicplayer.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.recyclerview.widget.RecyclerView;


import com.example.musicplayer.R;
import com.example.musicplayer.activity.MusicListActivity;
import com.example.musicplayer.entity.Music;
import com.example.musicplayer.service.MusicService;
import com.example.musicplayer.util.DbUtil;
import com.example.musicplayer.util.MusicNotification;

import java.util.List;

public class MusicAdapter extends RecyclerView.Adapter<MusicAdapter.ViewHolder> {

    private Context context;
    private TextView cacheMusicName;
    private TextView cacheArtistName;
    private TextView cacheAlbumName;
    private TextView cacheDot;
    private List<Music> mMusics;
    private MusicService.MusicBinder mMusicService = MusicService.getMusicService();
    private DbUtil mDbUtil = new DbUtil();

    public MusicAdapter(Context context, List<Music> musics) {
        this.context = context;
        this.mMusics = musics;
    }

    @NonNull
    @Override
    public MusicAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.music_list_item, parent, false);
        return new ViewHolder(view);
    }

    /**
     * Called by RecyclerView to display the data at the specified position. This method should
     * update the contents of the {@link ViewHolder#itemView} to reflect the item at the given
     * position.
     * <p>
     * Note that unlike {@link ListView}, RecyclerView will not call this method
     * again if the position of the item changes in the data set unless the item itself is
     * invalidated or the new position cannot be determined. For this reason, you should only
     * use the <code>position</code> parameter while acquiring the related data item inside
     * this method and should not keep a copy of it. If you need the position of an item later
     * on (e.g. in a click listener), use {@link ViewHolder#getAdapterPosition()} which will
     * have the updated adapter position.
     * <p>
     * Override {@link #onBindViewHolder(ViewHolder, int, List)} instead if Adapter can
     * handle efficient partial bind.
     *
     * @param holder   The ViewHolder which should be updated to represent the contents of the
     *                 item at the given position in the data set.
     * @param position The position of the item within the adapter's data set.
     */
    @Override
    public void onBindViewHolder(@NonNull final ViewHolder holder, final int position) {
        final Music music = mMusics.get(position);
        holder.musicName.setText(music.getName());
        holder.artistName.setText(music.getArtist());
        holder.albumName.setText(music.getArtist());
        // 点击列表后播放音乐
        holder.clickArea.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onClick(View v) {
                int index = mMusics.indexOf(music);
                mMusicService.setCurrentMusicList(mMusics, index);
                Intent intent = new Intent();
                intent.setAction(MusicNotification.ACTION_LIST);
                context.sendBroadcast(intent);
                // 设计样式
                if (cacheMusicName != null) {
                    setUnSelectedStyle(cacheMusicName);
                    setUnSelectedStyle(cacheArtistName);
                    setUnSelectedStyle(cacheAlbumName);
                    setUnSelectedStyle(cacheDot);
                }
                TextView musicName = v.findViewById(R.id.list_music_name);
                TextView artistName = v.findViewById(R.id.list_artist_name);
                TextView albumName = v.findViewById(R.id.list_album_name);
                TextView dot = v.findViewById(R.id.dot);
                setSelectedStyle(musicName);
                setSelectedStyle(artistName);
                setSelectedStyle(albumName);
                setSelectedStyle(dot);
                cacheMusicName = musicName;
                cacheArtistName = artistName;
                cacheAlbumName = albumName;
                cacheDot = dot;
            }
        });
        // 更多菜单选项
        holder.moreVert.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                PopupMenu popupMenu = new PopupMenu(context, v);
                popupMenu.getMenuInflater().inflate(R.menu.music_menu, popupMenu.getMenu());
                popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {
                            case R.id.add_to_music_list:
                                Music music = mMusics.get(position);
                                Intent intent = new Intent(context, MusicListActivity.class);
                                intent.putExtra("title", "歌单");
                                intent.putExtra("request_code", "action");
                                intent.putExtra("musicId", music.getId());
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                context.startActivity(intent);
                                break;
                            case R.id.delete_from_list:
                                Music deleteMusic = mMusics.get(position);
                                boolean isDeleted = mDbUtil.deleteMusicFromMusicList(context, deleteMusic.getId(), MusicListActivity.mTitle.getText().toString());
                                Log.i("==============", "歌单名称" + MusicListActivity.mTitle.getText().toString());
                                if (isDeleted) {
                                    mMusics.remove(position);
                                    notifyItemRemoved(position);
                                    notifyItemRangeChanged(position, mMusics.size());
                                }
                                break;
                            default:
                                break;
                        }
                        return true;
                    }
                });
                popupMenu.setOnDismissListener(new PopupMenu.OnDismissListener() {
                    @Override
                    public void onDismiss(PopupMenu menu) {

                    }
                });
                popupMenu.show();
            }
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    private void setSelectedStyle(TextView textView) {
        Log.i("==================", "设置了选中样式");
        textView.setTextColor(context.getResources().getColor(R.color.colorPrimary));
        textView.setSelected(true);
        textView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
        textView.setFocusable(true);
        textView.setFocusableInTouchMode(true);
        textView.setMarqueeRepeatLimit(-1);
        textView.setSingleLine(true);
    }

    private void setUnSelectedStyle(TextView textView) {
        Log.i("==================", "设置了未选中样式");
        textView.setTextColor(Color.GRAY);
        textView.setSelected(false);
        textView.setEllipsize(TextUtils.TruncateAt.END);
        textView.setFocusable(false);
        textView.setFocusableInTouchMode(false);
        textView.setMarqueeRepeatLimit(-1);
        textView.setSingleLine(true);
    }

    @Override
    public int getItemCount() {
        return mMusics.size();
    }

    static class ViewHolder extends RecyclerView.ViewHolder {
        TextView musicName; // 音乐名称
        TextView artistName;// 艺术家名称
        TextView albumName; // 专辑名称
        ImageView moreVert; // 更多按键
        LinearLayout clickArea; //点击区域
        View musicView;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);
            musicName = itemView.findViewById(R.id.list_music_name);
            artistName = itemView.findViewById(R.id.list_artist_name);
            albumName = itemView.findViewById(R.id.list_album_name);
            moreVert = itemView.findViewById(R.id.list_more);
            clickArea = itemView.findViewById(R.id.music_list_click_area);
            musicView = itemView;
        }
    }

}
